package com.LeeCode;

import java.util.Arrays;
import java.util.HashMap;

/**
 * 数组中的最大数对和
 */

public class Code2815 {
    public static void main(String[] args) {
        int[] nums = {51, 71, 17, 24, 42};
        System.out.println(new Code2815().maxSum1(nums));
    }

    public int maxSum(int[] nums) {
        int ans = -1;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int maxNum = 0, temp = nums[i];
            while (temp != 0) {
                maxNum = Math.max(maxNum, temp % 10);
                temp = temp / 10;
            }

            if (map.containsKey(maxNum)) {
                temp = map.get(maxNum);
                ans = Math.max(ans, temp + nums[i]);
            }
            map.put(maxNum, Math.max(temp, nums[i]));
        }
        return ans;
    }

    public int maxSum1(int[] nums) {
        int ans = -1;
        int[] cnt = new int[10];
        Arrays.fill(cnt, -1);
        for (int num : nums) {
            int maxNum = 0, temp = num;
            while (temp != 0) {
                maxNum = Math.max(maxNum, temp % 10);
                temp = temp / 10;
            }
            if (cnt[maxNum] != -1) {
                ans = Math.max(ans, cnt[maxNum] + num);
            }
            cnt[maxNum] = Math.max(num, cnt[maxNum]);

        }
        return ans;
    }
}
